package cn.ch.system.service.impl;

import cn.ch.basic.service.impl.BaseServiceImpl;
import cn.ch.system.domain.Role;
import cn.ch.system.mapper.RoleMapper;
import cn.ch.system.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Why
 * @since 2022-02-20
 */
@Service
public class RoleServiceImpl extends BaseServiceImpl<Role> implements IRoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public void add(Role role) {
        super.add(role);
        initRole(role);
    }

    private void initRole(Role role) {
        //1.移除原来的数据
        if(role.getId()!=null){
            roleMapper.batchRemoveMenu(role.getId());
            roleMapper.batchRemovePermission(role.getId());
        }
        //2.添加数据
        if (role.getMenus()!=null){
            Map<String, Object> map = new HashMap<>();
            map.put("roleId", role.getId());
            map.put("menuIds", role.getMenus());
            roleMapper.batchSaveMenu(map);
        }
        if (role.getPermissions()!=null){
            Map<String, Object> map = new HashMap<>();
            map.put("roleId", role.getId());
            map.put("permissionIds", role.getPermissions());
            roleMapper.batchSavePermission(map);
        }
    }

    @Override
    public void update(Role role) {
        super.update(role);
        initRole(role);
    }

    @Override
    public void remove(Long id) {
        super.remove(id);
    }
}
